package question6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @FileName Client
 * @Description
 * @Author Sword
 * @date 2024-12-24
 **/
public class Client {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 12345;
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        try {
            socket = new Socket(hostname, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            System.out.print("请输入要发送的数据（格式：名称,URL）: ");
            String userInput = stdIn.readLine();
            if (userInput != null) {
                out.println(userInput);

                String response;
                if ((response = in.readLine()) != null) {
                    System.out.println("服务器响应: " + response);
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("无法连接到主机: " + hostname);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stdIn != null) stdIn.close();
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
